import router from "@/router";
import { getToken } from "@/utils/auth";
import { ElButton } from "element-plus";
import { h } from "vue";

class WebSocketManager {
  private client: WebSocket | null = null;
  private messageHandlers: Map<string, ((message: string) => void)[]> = new Map();
  private reconnectAttempts = 0;
  private maxReconnectAttempts = 3; // 自定义最大重试次数
  private reconnectDelay = 5000; // 重试延迟（单位：毫秒）

  // 初始化 WebSocket 客户端
  setupWebSocket() {
    const endpoint = import.meta.env.VITE_APP_WS_ENDPOINT;

    // 如果没有配置 WebSocket 端点或显式关闭，直接返回
    if (!endpoint) {
      console.log("WebSocket 已被禁用，如需打开请在配置文件中配置 VITE_APP_WS_ENDPOINT");
      return;
    }

    if (this.client && this.client.OPEN) {
      console.log("客户端已存在并且连接正常");
      return this.client;
    }

    this.client = new WebSocket(`${endpoint}?access_token=${getToken().split(" ")[1]}`);

    this.client.onopen = () => {
      console.log(`连接到 WebSocket 服务器: ${endpoint}`);
      this.reconnectAttempts = 0; // 重置重连计数
      this.messageHandlers.forEach((handlers, topic) => {
        handlers.forEach((handler) => {
          this.subscribeToTopic(topic, handler);
        });
      });
    };

    this.client.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (data.event == "order_push_supplier") {
        ElNotification.success({
          title: "有新订单，请前往订单列表查看",
          message: () =>
            h(
              ElButton,
              {
                type: "primary",
                onClick: () => {
                  router.push({ path: "/order/order", query: { id: data.data.id } });
                },
              },
              "前往订单列表"
            ),
          duration: 5000, // 消息显示时间（单位：毫秒）
        });
      }
    };

    this.client.onerror = () => {};

    this.client.onclose = () => {
      console.log(`WebSocket 连接已断开: ${endpoint}`);
      this.reconnectAttempts++;
      if (this.reconnectAttempts < this.maxReconnectAttempts) {
        this.setupWebSocket();
        console.log(`正在尝试重连... 尝试次数: ${this.reconnectAttempts}`);
      } else {
        console.log("重连次数已达上限，停止重连");
        this.client?.close();
      }
    };
  }

  // 订阅主题
  public subscribeToTopic(topic: string, onMessage: (message: string) => void) {
    console.log(`正在订阅主题: ${topic}`);
    if (!this.client || !this.client.CONNECTING) {
      this.setupWebSocket();
    }

    if (this.messageHandlers.has(topic)) {
      this.messageHandlers.get(topic)?.push(onMessage);
    } else {
      this.messageHandlers.set(topic, [onMessage]);
    }
  }

  // 断开 WebSocket 连接
  public disconnect() {
    if (this.client) {
      console.log("断开 WebSocket 连接");
      this.client.close();
      this.client = null;
    }
  }
}

export default new WebSocketManager();
